<template>
  <doc-alert title="会员用户、标签、分组" url="https://doc.krcorecms.com/member/user/" />

  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="queryParams.nickname" class="!w-240px" clearable placeholder="请输入用户昵称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="queryParams.mobile" class="!w-240px" clearable placeholder="请输入手机号"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="注册时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-240px" end-placeholder="结束日期"
          start-placeholder="开始日期" type="daterange" value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item>
      <!-- <el-form-item label="登录时间" prop="loginDate">
        <el-date-picker v-model="queryParams.loginDate" :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px" end-placeholder="结束日期" start-placeholder="开始日期" type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss" />
      </el-form-item> -->
      <!-- <el-form-item label="用户标签" prop="tagIds">
        <MemberTagSelect v-model="queryParams.tagIds" />
      </el-form-item> -->
      <el-form-item label="用户等级" prop="levelId">
        <MemberLevelSelect v-model="queryParams.levelId" />
      </el-form-item>
      <el-form-item label="地区" prop="areaId">
        <el-cascader v-model="queryParams.areaName" :options="categoryList"
              :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }" class="w-1/1" clearable
              filterable placeholder="请选择区域" />
      </el-form-item>
      <el-form-item label="团长" prop="isTeam">
        <el-radio-group v-model="queryParams.isTeam">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="用户分组" prop="groupId">
        <MemberGroupSelect v-model="queryParams.groupId" />
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <!-- <el-button v-hasPermi="['promotion:coupon:send']" @click="openCoupon">发送优惠券</el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true" :stripe="true"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="40" />

      <el-table-column align="center" label="用户账户" prop="mobile" width="120px" />
      <el-table-column align="center" label="用户昵称" prop="nickname" width="120px" />
      <el-table-column align="center" label="注册地区" prop="areaName" width="180px" />
      <el-table-column align="center" label="是否商家" prop="isTeam" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.IS_NO" :value="scope.row.isBusiness" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否团长" prop="isTeam" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.IS_NO" :value="scope.row.isTeam" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="团长状态" prop="teamAudit" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.TEAM_AUDIT" :value="scope.row.teamAudit" />
        </template>
      </el-table-column>
      <el-table-column label="供求信息审核" align="center" prop="audit">
        <template #default="{ row }">
          <el-switch :value="row.audit" :active-value="1" :inactive-value="2" active-text="是" inactive-text="否"
            inline-prompt @click="handleStatusChange(row)" />
        </template>
      </el-table-column>
      <el-table-column :formatter="dateFormatter" align="center" label="入驻时间" prop="createTime" width="180px" />
 <!-- <el-table-column :formatter="dateFormatter" align="center" label="登录时间" prop="loginDate" width="180px" /> -->
 <!-- <el-table-column align="center" label="用户编号" prop="id" width="90px" /> -->
      <!-- 
      <el-table-column align="center" label="等级" prop="levelName" width="100px" />
      <el-table-column align="center" label="分组" prop="groupName" width="100px" />
      <el-table-column :show-overflow-tooltip="false" align="center" label="用户标签" prop="tagNames">
        <template #default="scope">
          <el-tag v-for="(tagName, index) in scope.row.tagNames" :key="index" class="mr-5px">
            {{ tagName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="积分" prop="point" width="100px" />
      <el-table-column align="center" label="头像" prop="avatar" width="80px">
        <template #default="scope">
                <img :src="scope.row.avatar" style="width: 40px" />
              </template>
      </el-table-column>
      -->
      <!-- 
      <el-table-column align="center" label="会员状态" prop="status" width="100px">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      -->
      <el-table-column :show-overflow-tooltip="false" align="center" fixed="right" label="操作" width="150px">
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button link type="primary" @click="openDetail(scope.row.id)">详情</el-button>

            <el-dropdown v-hasPermi="[
              'member:user:update',
              'member:user:update-level',
              'member:user:update-point',
              'member:user:update-balance'
            ]" @command="(command) => handleCommand(command, scope.row)">
              <el-button link type="primary">
                <Icon icon="ep:d-arrow-right" />
                更多
              </el-button>

              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="checkPermi(['member:user:update'])" command="handleUpdateTeam">
                    团长审核
                  </el-dropdown-item>
                  <el-dropdown-item v-if="checkPermi(['member:user:update'])" command="handleUpdate">
                    编辑用户
                  </el-dropdown-item>
                  <el-dropdown-item v-if="checkPermi(['member:user:update-level'])" command="handleUpdateLevel">
                    修改等级
                  </el-dropdown-item>
                  <!-- 
                  <el-dropdown-item v-if="checkPermi(['member:user:update-point'])" command="handleUpdatePoint">
                    修改积分
                  </el-dropdown-item>
                  <el-dropdown-item v-if="checkPermi(['member:user:update-balance'])" command="handleUpdateBlance">
                    修改余额(WIP)
                  </el-dropdown-item> 
                  -->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" :total="total"
      @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />
  <!-- 修改用户等级弹窗 -->
  <UserLevelUpdateForm ref="updateLevelFormRef" @success="getList" />

  <UserTeamUpdateForm ref="updateTeamFormRef" @success="getList" />
  <!-- 修改用户积分弹窗 -->
  <UserPointUpdateForm ref="updatePointFormRef" @success="getList" />
  <!-- 发送优惠券弹窗 -->
  <CouponSendForm ref="couponSendFormRef" />
</template>
<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import * as UserApi from '@/api/member/user'
import { DICT_TYPE } from '@/utils/dict'

import UserForm from './UserForm.vue'
import MemberLevelSelect from '@/views/member/level/components/MemberLevelSelect.vue'
import UserLevelUpdateForm from './UserLevelUpdateForm.vue'
import UserTeamUpdateForm from './UserTeamUpdateForm.vue'
import UserPointUpdateForm from './UserPointUpdateForm.vue'
import { CouponSendForm } from '@/views/mall/promotion/coupon/components'
import { checkPermi } from '@/utils/permission'
import { updateUser } from "@/api/member/user";
import { BusinessUserApi } from '@/api/wine/businessuser'

defineOptions({ name: 'MemberUser' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: null,
  mobile: null,
  loginDate: [],
  createTime: [],
  tagIds: [],
  levelId: null,
  groupId: null
})
const queryFormRef = ref() // 搜索的表单
const updateLevelFormRef = ref() // 修改会员等级表单
const updatePointFormRef = ref() // 修改会员积分表单
const updateTeamFormRef = ref() // 修改会员积分表单
const selectedIds = ref<number[]>([]) // 表格的选中 ID 数组

const categoryList = ref()
const creditOption = ref<ListItem[]>([])

const initCreditOption = async () => {
  const data = await BusinessUserApi.getCreditList({})
  creditOption.value = []
  data.map((item) => {
    creditOption.value.push({
      label: item.name,
      value: item.id
    })
  })
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 打开会员详情 */
const { push } = useRouter()
const openDetail = (id: number) => {
  push({ name: 'MemberUserDetail', params: { id } })
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 表格选中事件 */
const handleSelectionChange = (rows: UserApi.UserVO[]) => {
  selectedIds.value = rows.map((row) => row.id)
}

/** 发送优惠券 */
const couponSendFormRef = ref()
const openCoupon = () => {
  if (selectedIds.value.length === 0) {
    message.warning('请选择要发送优惠券的用户')
    return
  }
  couponSendFormRef.value.open(selectedIds.value)
}

const handleStatusChange = async (row: any) => {
  try {
    let data = row
    // 二次确认
    const text = data.audit == 1 ? '关闭' : '打开'
    await message.confirm(`确认要${text}"${row.nickname}"的审核权限吗？`).then(async (res) => {
      console.log("err", res);
      data.audit = data.audit == 1 ? 2 : 1
      // 发起修改
      await updateUser(data)
      message.success('操作成功')
      // 刷新列表
      await getList()
    }).catch((err) => {
      console.log("err", err);
    })
  } catch {
    // 异常时，需要重置回之前的值
    await getList()
  }
}
/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleUpdate':
      openForm('update', row.id)
      break
    case 'handleUpdateLevel':
      updateLevelFormRef.value.open(row.id)
      break
    case 'handleUpdatePoint':
      updatePointFormRef.value.open(row.id)
      break
    case 'handleUpdateBlance':
      // todo @jason：增加一个【修改余额】
      break
    case 'handleUpdateTeam':
      updateTeamFormRef.value.open(row.id)
      break
    default:
      break
  }
}

/** 初始化 **/
onMounted(async () => {
  getList()
  await initCreditOption()
  const data = await BusinessUserApi.getCategoryList({})
  categoryList.value = data
})
</script>
